package com.practice.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.practice.reggie.common.CustomException;
import com.practice.reggie.common.R;
import com.practice.reggie.dto.SetmealDto;
import com.practice.reggie.entity.Category;
import com.practice.reggie.entity.Dish;
import com.practice.reggie.entity.Setmeal;
import com.practice.reggie.entity.SetmealDish;
import com.practice.reggie.service.CategoryService;
import com.practice.reggie.service.DishService;
import com.practice.reggie.service.SetmealDishService;
import com.practice.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 套餐保存
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("添加套餐参数==》"+setmealDto);
        setmealService.saveAndSetmDish(setmealDto);
        return R.success("保存成功！");
    }

    /**
     * 套餐分页查询
     * @param
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //创建分页构造器
        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //添加排序
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(setmealPage,queryWrapper);
        //数据处理
        List<Setmeal> setmealList = setmealPage.getRecords().stream().map((item) -> {
            //获取绑定套餐id
            Long categoryId = item.getCategoryId();
            //查询绑定套餐名称
            Category category = categoryService.getById(categoryId);
            //set套餐名称
            if (category != null) {
                item.setCategoryName(category.getName());
            }
            return item;
        }).collect(Collectors.toList());

        //重新set数据
        setmealPage.setRecords(setmealList);
        //返回
        return R.success(setmealPage);
    }

    /**
     * 批量停售起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateState(@PathVariable int status,String[] ids){
        log.info("flag:"+status +" ids:"+ids);
        //数据判断
        if(ids==null || ids.length==0){
            throw new CustomException("参数有误");
        }
        //条件构造器
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Setmeal::getStatus,status).in(Setmeal::getId,ids);

        setmealService.update(updateWrapper);

        String flag = status == 0 ? "已禁售" : "已启售";

        return R.success(flag);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache" ,allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        //调用自定义删除方法
        setmealService.removeWithDish(ids);
        return R.success("删除成功！");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        //根据套餐分类ID（category_id）
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        //没有停售的套餐
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 套餐详情---------
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<SetmealDto> getSetmealDto(@PathVariable Long id){
        log.info("id查询:{}", id);
        SetmealDto setmealDtos = setmealService.getByIdWithDish(id);
        List<Dish> dishList = dishService.list();
        //填充image属性
        List<SetmealDish> setmealDishes = setmealDtos.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            for (Dish dish : dishList) {
                if(dish.getId() .equals(setmealDish.getDishId())){
                    setmealDish.setImage(dish.getImage());
                }
            }
        }
        return R.success(setmealDtos);
    }
}    